package com.huawei.zyb.taskManager.application.service;

import com.huawei.zyb.taskManager.application.service.dto.ReferenceDocumentDTO;
import com.huawei.zyb.taskManager.domain.requirement.entity.ReferenceDocument;
import com.huawei.zyb.taskManager.domain.requirement.repository.ReferenceDocumentRepository;
import com.huawei.zyb.taskManager.domain.requirement.valueobject.ReferenceDocumentId;
import com.huawei.zyb.taskManager.domain.requirement.valueobject.RequirementId;
import com.huawei.zyb.taskManager.domain.requirement.valueobject.DocumentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 参考文档应用服务
 */
@Service
@Transactional
public class ReferenceDocumentApplicationService {

    @Autowired
    private ReferenceDocumentRepository referenceDocumentRepository;

    /**
     * 创建参考文档
     */
    public ReferenceDocumentDTO createReferenceDocument(String requirementId, String title, String url, String description, String type, String uploader) {
        try {
            // 生成文档ID
            ReferenceDocumentId documentId = ReferenceDocumentId.of("DOC-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase());
            
            // 创建文档实体
            ReferenceDocument document = ReferenceDocument.create(
                documentId,
                RequirementId.of(Long.parseLong(requirementId)),
                title,
                url,
                description,
                DocumentType.fromCode(type),
                uploader
            );
            
            // 保存文档
            ReferenceDocument savedDocument = referenceDocumentRepository.save(document);
            
            return convertToDTO(savedDocument);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的需求ID: " + requirementId, e);
        } catch (Exception e) {
            throw new RuntimeException("创建参考文档失败: " + e.getMessage(), e);
        }
    }

    /**
     * 根据需求ID查找参考文档
     */
    @Transactional(readOnly = true)
    public List<ReferenceDocumentDTO> findByRequirementId(String requirementId) {
        try {
            RequirementId reqId = RequirementId.of(Long.parseLong(requirementId));
            List<ReferenceDocument> documents = referenceDocumentRepository.findByRequirementId(reqId);
            return documents.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的需求ID: " + requirementId, e);
        }
    }

    /**
     * 根据文档ID查找参考文档
     */
    @Transactional(readOnly = true)
    public Optional<ReferenceDocumentDTO> findByDocumentId(String documentId) {
        ReferenceDocumentId docId = ReferenceDocumentId.of(documentId);
        Optional<ReferenceDocument> document = referenceDocumentRepository.findById(docId);
        return document.map(this::convertToDTO);
    }

    /**
     * 更新参考文档
     */
    public ReferenceDocumentDTO updateReferenceDocument(String documentId, String title, String url, String description, String type) {
        ReferenceDocumentId docId = ReferenceDocumentId.of(documentId);
        Optional<ReferenceDocument> optionalDocument = referenceDocumentRepository.findById(docId);
        
        if (optionalDocument.isEmpty()) {
            throw new IllegalArgumentException("参考文档不存在: " + documentId);
        }
        
        ReferenceDocument document = optionalDocument.get();
        document.updateInfo(title, url, description, DocumentType.fromCode(type));
        
        ReferenceDocument savedDocument = referenceDocumentRepository.save(document);
        return convertToDTO(savedDocument);
    }

    /**
     * 删除参考文档
     */
    public void deleteReferenceDocument(String documentId) {
        ReferenceDocumentId docId = ReferenceDocumentId.of(documentId);
        referenceDocumentRepository.deleteById(docId);
    }

    /**
     * 增加查看次数
     */
    public void incrementViewCount(String documentId) {
        ReferenceDocumentId docId = ReferenceDocumentId.of(documentId);
        Optional<ReferenceDocument> optionalDocument = referenceDocumentRepository.findById(docId);
        
        if (optionalDocument.isPresent()) {
            ReferenceDocument document = optionalDocument.get();
            document.incrementViewCount();
            referenceDocumentRepository.save(document);
        }
    }

    /**
     * 根据上传者查找参考文档
     */
    @Transactional(readOnly = true)
    public List<ReferenceDocumentDTO> findByUploader(String uploader) {
        List<ReferenceDocument> documents = referenceDocumentRepository.findByUploader(uploader);
        return documents.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为DTO
     */
    private ReferenceDocumentDTO convertToDTO(ReferenceDocument document) {
        return new ReferenceDocumentDTO(
            document.getId().getValue(),
            document.getRequirementId().getValue().toString(),
            document.getTitle(),
            document.getUrl(),
            document.getDescription(),
            document.getType().getCode(),
            document.getUploader(),
            document.getViewCount(),
            document.getCreatedAt(),
            document.getUpdatedAt()
        );
    }
}